from kcluster import kcluster, test

from topo import topo

class hosts:
    def __init__(self):
        self.quantity = 0
        self.topo = topo()
        self.v2h = {}
        self.h2v = {}
        self.h2slot = {}
        self.clusters = []
        self.nodes = []
        self.matrix = {}
    def load(self, hostf, topof):
        hfile = open(hostf, 'r')
        hostlines = hfile.readlines()
        for hostline in hostlines:
            tricell = hostline.split()
            if len(tricell) == 1:
                self.quantity = int(tricell[0])
            if len(tricell) == 2:
                self.h2slot[int(tricell[0])] = int(tricell[1])
                self.h2v[int(tricell[0])] = []
                self.nodes.append(int(tricell[0]))
        hfile.close()
        self.topo.load(topof)
        self.topo.floyd_warshall()
    def place(self, vm, host):
        if self.v2h.has_key(vm):
            #print str(vm) + ' has been placed elsewhere'
            return False
        if len(self.h2v[host]) >= self.h2slot[host]:
            #print str(host) + ' has no more place for ' + str(vm)
            return False
        self.h2v[host].append(vm)
        self.v2h[vm] = host
        #print self.v2h
    def remove(self, vm, host):
        if self.v2h[vm] == host:
            self.v2h.pop(vm)
            self.h2v[host].remove(vm)
            return True
        else:
            return False
    def clear(self):
        self.v2h.clear()
        for key in self.h2v.keys():
            self.h2v[key] = []
    def distance(self, i, j):
        #print i, j
        #print self.v2h[i], self.v2h[j]
        if i == j:
            return 0
        if self.v2h[i] == self.v2h[j]:
            return 0
        return self.topo.distance[(self.v2h[i], self.v2h[j])]
    def cluster(self):
        self.matrix = {}
        for key, value in self.topo.distance.items():
            if (key[0] in self.nodes) and (key[1] in self.nodes):
                if (self.matrix.has_key(key[0])):
                    self.matrix[key[0]][key[1]] = value
                else:
                    self.matrix[key[0]] = {}
                    self.matrix[key[0]][key[1]] = value
                if (self.matrix.has_key(key[1])):
                    self.matrix[key[1]][key[0]] = value
                else:
                    self.matrix[key[1]] = {}
                    self.matrix[key[1]][key[0]] = value
        #print self.matrix
        print self.nodes
        self.clusters = kcluster(self.matrix, 4, self.nodes)
        #test(self.matrix, self.clusters, self.nodes)
        #test(self.matrix, [set([20, 21, 22, 23]), set([24,25,26,27]), set([28,29,30,31]), set([32,33,34,35])], self.nodes)
    def partialCluster(self, k, subnodes):
        return kcluster(self.matrix, k, subnodes)
#hs = hosts()
#hs.load('../host.in', '../topo.in')
#hs.cluster()
#print hs.clusters
